package com.ia2014.tp.portal2.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ia2014.tp.portal2.facades.FacadeIntegracion;
import com.ia2014.tp.portal2.vo.ItemVentaVO;
import com.ia2014.tp.portal2.vo.VentaVO;
/**
 * Realiza de los objetos de portal para 
 * @author DiegoAlejandro
 *
 */
@WebServlet("/verVenta")
public class VerVentaServlet extends AbstractServlet {
	private static final long serialVersionUID = -2807780651707180197L;
	
	@EJB
	private FacadeIntegracion facade;

	public VerVentaServlet(){
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		this.comprobarSession(req, resp);
		this.process(req, resp);
	
	}	

	private void process(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		
		HttpSession session = req.getSession(false);
		Map<Integer, VentaVO> ventasVO = this.getMapVentasFromSession(session);
		Integer nroVenta = Integer.parseInt(req.getParameter("nroVenta"));
		VentaVO ventaVO = ventasVO.get(nroVenta);
		
		if (ventaVO == null){
			ventaVO = this.facade.getVentaByNro(nroVenta);
		}
		
		if (ventaVO != null && (ventaVO.getItems() == null || ventaVO.getItems().isEmpty())){
			List<ItemVentaVO> items = this.facade.getItemsByVenta(nroVenta);
			if (items == null){
				items = new ArrayList<ItemVentaVO>();
			}
			ventaVO.setItems(items);
		}
		
		session.setAttribute("ventaVO", ventaVO);
		resp.sendRedirect("venta.jsp");
	}
}
